<template>
  <div class="dashboard-page">
    <h2>数据概览</h2>

    <!-- 统计卡片 - 今日数据 -->
    <div v-loading="loading" class="stats-section">
      <h3>今日数据</h3>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card today">
            <div class="stat-icon">
              <el-icon :size="40"><Tickets /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.todayStats?.orderCount || 0 }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card today">
            <div class="stat-icon">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ dashboard.todayStats?.salesAmount || 0 }}</div>
              <div class="stat-label">今日销售额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card today">
            <div class="stat-icon">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.todayStats?.newCustomers || 0 }}</div>
              <div class="stat-label">新增客户</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card today">
            <div class="stat-icon">
              <el-icon :size="40"><Box /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.todayStats?.productsSold || 0 }}</div>
              <div class="stat-label">售出商品</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 统计卡片 - 本月数据 -->
    <div v-loading="loading" class="stats-section">
      <h3>本月数据</h3>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card month">
            <div class="stat-icon">
              <el-icon :size="40"><Tickets /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.monthStats?.orderCount || 0 }}</div>
              <div class="stat-label">本月订单</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card month">
            <div class="stat-icon">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ dashboard.monthStats?.salesAmount || 0 }}</div>
              <div class="stat-label">销售额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card month">
            <div class="stat-icon">
              <el-icon :size="40"><RefreshLeft /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ dashboard.monthStats?.refundAmount || 0 }}</div>
              <div class="stat-label">退款金额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card month">
            <div class="stat-icon">
              <el-icon :size="40"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ dashboard.monthStats?.netSales || 0 }}</div>
              <div class="stat-label">净销售额</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 统计卡片 - 总体数据 -->
    <div v-loading="loading" class="stats-section">
      <h3>总体数据</h3>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-icon">
              <el-icon :size="40"><Box /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.totalStats?.totalProducts || 0 }}</div>
              <div class="stat-label">商品总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-icon">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.totalStats?.totalCustomers || 0 }}</div>
              <div class="stat-label">客户总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-icon">
              <el-icon :size="40"><UserFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ dashboard.totalStats?.totalEmployees || 0 }}</div>
              <div class="stat-label">员工总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-icon">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ dashboard.totalStats?.totalSales || 0 }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 销售趋势图 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>销售趋势（最近7天）</span>
            </div>
          </template>
          <div id="salesTrendChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>

      <!-- 热销商品 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热销商品 TOP 5</span>
            </div>
          </template>
          <div class="hot-products">
            <div v-for="(product, index) in dashboard.hotProducts" :key="product.productId" class="hot-product-item">
              <div class="rank" :class="'rank-' + (index + 1)">{{ index + 1 }}</div>
              <el-image :src="product.productImage || '/default-product.png'" class="product-image" fit="cover" />
              <div class="product-info">
                <div class="product-name">{{ product.productName }}</div>
                <div class="product-stats">
                  <span>销量: {{ product.sales }}</span>
                  <span>收入: ¥{{ product.revenue }}</span>
                </div>
              </div>
            </div>
            <el-empty v-if="!dashboard.hotProducts || dashboard.hotProducts.length === 0" description="暂无数据" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 库存预警 -->
    <el-card v-if="dashboard.stockWarnings && dashboard.stockWarnings.length > 0" class="warnings-section">
      <template #header>
        <div class="card-header">
          <el-icon><Warning /></el-icon>
          <span>库存预警</span>
        </div>
      </template>
      <el-table :data="dashboard.stockWarnings" stripe style="width: 100%">
        <el-table-column prop="productId" label="商品ID" width="100" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="stock" label="当前库存" width="120">
          <template #default="{ row }">
            <el-tag type="danger">{{ row.stock }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="120">
          <template #default="{ row }">
            <span>{{ row.minStock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="goToProduct(row.productId)">
              补货
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getAdminDashboard } from '@/api/dashboard'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const router = useRouter()
const loading = ref(false)
const dashboard = reactive({
  todayStats: null,
  monthStats: null,
  totalStats: null,
  salesTrend: [],
  hotProducts: [],
  stockWarnings: []
})

let chartInstance = null

// 加载仪表盘数据
const loadDashboard = async () => {
  loading.value = true
  try {
    const res = await getAdminDashboard()
    if (res.code === 200) {
      Object.assign(dashboard, res.data)
      
      // 渲染图表
      if (dashboard.salesTrend && dashboard.salesTrend.length > 0) {
        await nextTick()
        renderSalesTrendChart()
      }
    } else {
      ElMessage.error(res.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 渲染销售趋势图
const renderSalesTrendChart = () => {
  const chartDom = document.getElementById('salesTrendChart')
  if (!chartDom) return
  
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartDom)
  
  const dates = dashboard.salesTrend.map(item => item.date)
  const salesData = dashboard.salesTrend.map(item => item.salesAmount || 0)
  const orderData = dashboard.salesTrend.map(item => item.orderCount || 0)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['销售额', '订单数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额（元）',
        position: 'left'
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: salesData,
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: orderData,
        smooth: true,
        itemStyle: {
          color: '#409eff'
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
  
  // 窗口大小改变时重新渲染
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
}

// 跳转到商品页面
const goToProduct = (productId) => {
  router.push(`/admin/products?productId=${productId}`)
}

onMounted(() => {
  loadDashboard()
})
</script>

<style scoped lang="scss">
.dashboard-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #666;
    font-weight: 500;
  }

  .stats-section {
    margin-bottom: 30px;

    .stat-card {
      cursor: default;
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-4px);
      }

      :deep(.el-card__body) {
        display: flex;
        align-items: center;
        padding: 20px;
      }

      .stat-icon {
        margin-right: 20px;
        opacity: 0.8;
      }

      .stat-content {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 8px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }

      &.today {
        .stat-icon {
          color: #409eff;
        }
        .stat-value {
          color: #409eff;
        }
      }

      &.month {
        .stat-icon {
          color: #67c23a;
        }
        .stat-value {
          color: #67c23a;
        }
      }

      &.total {
        .stat-icon {
          color: #e6a23c;
        }
        .stat-value {
          color: #e6a23c;
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 20px;

    .card-header {
      font-size: 16px;
      font-weight: bold;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .hot-products {
      .hot-product-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        .rank {
          width: 28px;
          height: 28px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bold;
          margin-right: 12px;
          background: #909399;
          color: white;
          font-size: 14px;

          &.rank-1 {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #333;
          }

          &.rank-2 {
            background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
            color: #333;
          }

          &.rank-3 {
            background: linear-gradient(135deg, #cd7f32 0%, #e8b67f 100%);
            color: white;
          }
        }

        .product-image {
          width: 50px;
          height: 50px;
          border-radius: 4px;
          margin-right: 12px;
        }

        .product-info {
          flex: 1;

          .product-name {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .product-stats {
            font-size: 12px;
            color: #909399;
            display: flex;
            gap: 12px;
          }
        }
      }
    }
  }

  .warnings-section {
    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #f56c6c;
      font-weight: bold;
    }
  }
}
</style>
